import { httpRequest } from "../../utils/network/network";

import Notify from "@vant/weapp/notify/notify";
import { API } from "../../utils/network/api";
import { calculateDaysDifferenceUtils, checkUserAuthUtils } from "../../utils/index";

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    loginStatus: app.globalData.loginStatus,
    emptyBgCalceldar: app.globalData.emptyBgCalceldar,
    calendarList: [],
    id: "",
    title: "",
    cover: "",
    calendarType: "COUNTDOWN",
    time: "",
    times: "",
    visibleCalendarPopup: false,
    showCalendar: false,
    relationRadio: app.globalData.relationRadio,
    calendarRadio: app.globalData.calendarRadio,
    visibleRange: "LOVERS",
    minDate: new Date(2018, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    popupType: "add",
    pageNum: 1,
    pageSize: 6,
    fileList: [],
    defaultDate: new Date()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.calendarList = [];
    this.getCalendarList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (!this.data.loginStatus) {
      this.setData({
        loginStatus: app.globalData.loginStatus
      })
      this.onLoad();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.data.pageNum = 1;
    this.data.pageSize = 6;
    this.data.calendarList = [];
    this.getCalendarList();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 500);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.data.pageNum++;
    this.getCalendarList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  async getCalendarList() {
    if (!this.data.loginStatus) {
      return;
    }
    let params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize
    }
    let calendarList = this.data.calendarList;
    const res = await httpRequest(API.calendarList, params);
    if (res.data.recordedList) {
      res.data.recordedList.forEach(item => {
        item.time = item.times.split(" ")[0];
        item._date = calculateDaysDifferenceUtils(item.times, item.calendarType);
      })
    }
    calendarList.push(...res.data.recordedList);
    this.setData({
      calendarList
    })
  },
  formatDate(value) {
    let date = new Date(value);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    const time = y + '-' + m + '-' + d;
    return {
      times: `${time} 00:00:00`,
      time
    };
  },
  changeCaneldar() {
    this.setData({
      showCalendar: !this.data.showCalendar
    })
  },
  confirmDate(e) {
    let date = this.formatDate(e.detail);
    this.setData({
      showCalendar: !this.data.showCalendar,
      times: date.times,
      time: date.time
    });
  },
  changeRidao() {
    this.setData({
      times: "",
      time: ""
    })
  },
  // 添加日历
  showVisible() {
    this.setData({
      visibleCalendarPopup: !this.data.visibleCalendarPopup
    })
    if (!this.data.visibleCalendarPopup) {
      this.clearForm();
    }
  },
  async createAndUpdateCalendar() {
    const uploadImageComponent = this.selectComponent("#upload_calendar_image");
    let params = {
      id: this.data.id,
      title: this.data.title,
      calendarType: this.data.calendarType,
      visibleRange: this.data.visibleRange,
      times: this.data.times,
      cover: null,
      remark: this.data.remark,
    }
    if (!params.title || !params.calendarType || !params.times || !params.visibleRange || !uploadImageComponent.getImageList().length) {
      Notify({
        duration: app.globalData.notifyDuration,
        type: "warning",
        message: "请填入必填项"
      })
      return;
    }
    // upload image
    const fileList = await uploadImageComponent.uploadImage();
    params.cover = fileList[0].filePath;

    const calendarStatusDict = {
      "add": "添加",
      "update": "更新"
    }
    const popupType = this.data.popupType;
    let _this = this;
    httpRequest(popupType == "add" ? API.calendarAdd : API.calendarUpdate, params, "POST", "application/json").then(res => {
      Notify({
        duration: app.globalData.notifyDuration,
        type: "success",
        message: res.message,
        onClose: () => {
          _this.showVisible();
          _this.data.calendarList = [];
          _this.data.pageNum = 1;
          _this.data.pageSize = 6;
          _this.getCalendarList();
          // init
          _this.setData({
            popupType: "add"
          })
        }
      })
    })
      .catch(err => {
        wx.showModal({
          title: `${calendarStatusDict[popupType]}失败`,
          content: err.message || `${calendarStatusDict[popupType]}失败`,
          showCancel: false
        })
      })
  },
  clearForm() {
    this.setData({
      id: "",
      title: "",
      calendarType: "COUNTDOWN",
      times: "",
      visibleRange: "LOVERS",
      fileList: [],
      time: "",
      times: "",
      cover: "",
      defaultDate: new Date()
    })
  },
  getCalendarMenus(e) {
    const item = e.currentTarget.dataset.item;
    let that = this;
    wx.showActionSheet({
      itemList: ["详情", "更新", "删除"],
      async success(res) {
        switch (res.tapIndex) {
          case 0:
            Notify({
              duration: app.globalData.notifyDuration,
              type: "warning",
              message: "敬请期待该功能～",
            })
            break;
          case 1:
            const res = await that.getCalendarInfo(item.id);
            that.setData({
              id: res.id,
              title: res.title,
              calendarType: res.calendarType,
              time: res.times.split(" ")[0],
              times: res.times,
              defaultDate: res.times.split(" ")[0],
              fileList: [{
                status: "done",
                url: res.cover,
                filePath: res.cover
              }],
              remark: res.remark,
              visibleRange: res.visibleRange,
              popupType: "update"
            })
            that.showVisible();
            break;
          // delete calendar
          case 2:
            if (!checkUserAuthUtils(item.userId, app.showNoAuthMessage, "日历")) return;
            httpRequest(`${API.calendar}/${item.id}`, {}, "DELETE").then(res => {
              Notify({
                type: "success",
                duration: app.globalData.notifyDuration,
                message: res.message,
                onClose: () => {
                  that.data.calendarList = [];
                  that.data.pageNum = 1;
                  that.data.pageSize = 6;
                  that.getCalendarList();
                }
              })
            }).catch(err => {
              wx.showModal({
                title: "删除失败",
                content: err.message || "删除失败",
                showCancel: false,
              })
            })
            break;
          default:
            Notify({
              duration: app.globalData.notifyDuration,
              type: "warning",
              message: "敬请期待该功能～"
            })
        }
      },
    })

  },
  cancelLogin(e) {
    this.setData({
      show: e.detail.show
    })
  },
  changeShow() {
    this.setData({
      show: !this.data.show
    })
  },
  successLogin() {
    this.setData({
      loginStatus: wx.getStorageSync("loginStatus"),
      show: false
    })
    this.data.calendarList = [];
    this.getCalendarList();
  },
  async getCalendarInfo(id) {
    return (await httpRequest(`${API.calendar}/${id}`)).data;
  }
})